var numberOfAcquisitions = 20;
var queryBluetoothCount = 50;
var deviceName = null;
var deviceId = null;
var services = null;
var notifyUuid = null;
var characteristicId = null;
var monitoringStatus = false;
var pageStatus = false;
var connectionStatus = -1;
var bluetoothSwitchPrompt = true;
var getBluetoothStatusInterval = 0;
import $api from '@/common/request/index'
import { eventBus } from '@/main.js'
export default {
	//监听蓝牙连接状态
	startBLEConnectionStateListening(deviceNo) {
		var that = this;
		console.log('是否监听',monitoringStatus)
		if (!monitoringStatus){
			uni.onBLEConnectionStateChange((res) => {
				console.log('监听蓝牙的状态',res)
				if (!res.connected) {
					eventBus.$emit('connectionStatus', 3)
					connectionStatus = 3;
					console.log("蓝牙关掉啦")
					that.checkBluetoothState(deviceNo);
				}
			});
			monitoringStatus = true;
		}
	},
	//关掉蓝牙连接
	closeBluetoothAdapter(){
		console.log("关掉蓝牙连接")
		uni.closeBluetoothAdapter({
			success(res) {
				eventBus.$emit('connectionStatus', 3)
				connectionStatus = 3;
				console.log('成功关掉蓝牙连接',res)
			},
			fail(res){
				console.log('关掉蓝牙连接失败',res)
			}
		})
	},
	//创建页面切换后台,前台监听
	createAPageListener(deviceNo){
		var that = this;
		if (!pageStatus && !uni.$u.test.isEmpty(deviceNo)){
			//切换到后台 关掉蓝牙连接
			wx.onAppEnterBackground(() => {
				if (getApp().globalData.isItTriggered){
					console.log("触发onAppEnterBackground后台函数")
					that.closeBluetoothAdapter();
				}
			});
			pageStatus = true;
		}
	},
	//死循环间隔两秒执行一次 直到蓝牙打开
	checkBluetoothState(deviceNo) {
		var that = this;
		uni.getBluetoothAdapterState({
			success(res) {
				console.log('checkBluetoothState获取蓝牙状态', res);
				if (res.available) {
					that.initBluetooth(deviceNo, true);
				} else {
					setTimeout(() => {
						that.checkBluetoothState(deviceNo);
					}, 2000)
				}
			},
		});
	},
	//断开提示,用户点击退出 则退到上一个页面
	disconnectPrompt(){
		var that = this;
		uni.showModal({
			title: '提示',
			confirmText: '重新连接',
			cancelText: '退出',
			content: '蓝牙连接设备失败，是否重新建立连接？',
			success: function (res) {
				connectionStatus = 3;
				if (res.confirm) {
					that.initBluetooth(deviceName, true);
				} else{
					uni.navigateBack({
						delta: 1
					});
				}
			}
		});
	},
	// 初始化蓝牙
	initBluetooth(deviceNo,isBluetooth){
		queryBluetoothCount = 40;
		numberOfAcquisitions = 10;
		console.log('连接状态',connectionStatus)
		if(isBluetooth && connectionStatus !== 1 && !uni.$u.test.isEmpty(deviceNo)){
			eventBus.$emit('connectionStatus', 1)
			connectionStatus = 1;
			deviceName = deviceNo;
			var that = this;
			setTimeout(() => {
				uni.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口
					success: function(res) {
						getBluetoothStatusInterval = 0;
						that.findBlue();
					},
					fail: function(res) {
						getBluetoothStatusInterval = 0;
						uni.authorize({
							scope: 'scope.bluetooth',
							success: function () {
								// 用户同意授权后再次尝试打开蓝牙适配器
								uni.openBluetoothAdapter({
									success: function (res) {
										that.findBlue();
									},
									fail: function (err) {
										eventBus.$emit('connectionStatus', 3)
										connectionStatus = 3;
										if (!bluetoothSwitchPrompt){
											return;
										}
										uni.showModal({
											title: '提示',
											confirmText: '打开',
											cancelText: '退出',
											content: '请检查手机蓝牙是否打开？',
											success: function (res) {
												that.checkBluetoothState(deviceNo);
												bluetoothSwitchPrompt = false;
												if (res.confirm) {
													getBluetoothStatusInterval = 2000;
													let port = uni.getSystemInfoSync().platform
													bluetoothSwitchPrompt = true
													switch (port) {
														case 'android':
															uni.openSystemBluetoothSetting({
																success: function(res) {
																	console.log("跳转蓝牙设置android", res);
																},
															})
															break;
														case 'ios':
															uni.openAppAuthorizeSetting({
																success (res) {
																	console.log("跳转蓝牙设置ios", res);
																}
															})
															break;
													}
												}else{
													bluetoothSwitchPrompt = true;
													uni.navigateBack({
														delta: 1
													});
												}
											}
										});
									}
								});
							},
							fail: function () {
								that.showBluetoothSetting();
							}
						});
					}
				})
			},getBluetoothStatusInterval)
		}
	},
	
	showBluetoothSetting() {
	  uni.showModal({  
	    title: '提示',  
	    content: '需要打开蓝牙以使用此功能，是否前往设置？',  
	    success: function (res) {  
	      if (res.confirm) {  
	        // 用户点击了“确定”，跳转到蓝牙设置页面  
			uni.openSetting(); 
	      }  
	    }  
	  });  
	},
	
	findBlue() {
		var that = this
		uni.startBluetoothDevicesDiscovery({
			allowDuplicatesKey: false,
			interval: 0,
			success: function(res) {
				that.getBlue() //3.0
			}
		})
	},
	
	getBlue() {
		var that = this;
		var isItFound = false;
		uni.showLoading({
			title: '正在搜索设备中...',
		})
		setTimeout(() => {
			//uni.getBluetoothDevices获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备
			uni.getBluetoothDevices({
				success: function(res) {
					//res.devices=[] 没有获取到一个蓝牙设备认定未没授权微信蓝牙权限
					if (uni.$u.test.isEmpty(res.devices)){
						numberOfAcquisitions--;
					}
					const foundDevice = res.devices.find(data => data.name === deviceName);
					if (foundDevice) {
						uni.hideLoading();
						uni.showLoading({
							title: '正在与设备建立连接...',
						})
						console.log('找到匹配的蓝牙设备', foundDevice.name);
						deviceId = foundDevice.deviceId;
						isItFound = true;
						that.linkBluetooth();
					} else {
						// uni.showLoading({title: "没有找到" + deviceName + '设备,剩余查找次数' + queryBluetoothCount})
						console.log("没有找到" + deviceName + '设备,剩余查找次数' + queryBluetoothCount)
						queryBluetoothCount--;
					}
					if(queryBluetoothCount === 0){
						uni.hideLoading();
						eventBus.$emit('connectionStatus', 3)
						connectionStatus = 3;
						uni.showModal({
							title: '提示',
							confirmText: '重新连接',
							cancelText: '退出',
							content: '蓝牙连接设备失败，是否重新建立连接？',
							success:function (res){
								if (res.confirm) {
									//关闭再重新
									uni.stopBluetoothDevicesDiscovery({
										success: function(res) {
											console.log('关闭蓝牙搜索，重新连接设备' + deviceName);
										}
									})
									that.initBluetooth(deviceName,true)
								}
							}
						});
						return;
					}
					if (numberOfAcquisitions === 0){
						uni.hideLoading();
						eventBus.$emit('connectionStatus', 3)
						connectionStatus = 3;
						uni.showModal({
							title: '提示',
							content: '链接蓝牙失败，请检查是否打开微信蓝牙权限',
							confirmText: '去设置',
							cancelText: '退出',
							success:function (res){
								if (res.confirm) {
									uni.openAppAuthorizeSetting({
										success (res) {
											console.log(res)
										}
									})
								}else{
									uni.navigateBack({
										delta: 1
									});
								}
							}
						});
						return;
					}
					if (!isItFound && numberOfAcquisitions !== 0 && queryBluetoothCount !== 0){
						that.getBlue();
					}
				},
				fail: function() {
					console.log("搜索蓝牙设备失败")
				}
			})
		},200)
	},

	linkBluetooth(){
		var that = this
		uni.createBLEConnection({
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: deviceId, //设备id
			success: function(res) {
				uni.hideLoading();
				uni.showToast({
				title: '连接成功',
				icon: 'fails',
				duration: 800
			})
			console.log("连接蓝牙成功!-->11111")
			uni.stopBluetoothDevicesDiscovery({
				success: function(res) {
					console.log('连接蓝牙成功之后关闭蓝牙搜索');
				}
			})
			that.getServiceId() //5.0
			},
			fail: function (res) {
				uni.hideLoading();
				console.log("createBLEConnection",res)
			}  
		})
	},
	
	getServiceId() {
		var that = this;
		uni.getBLEDeviceServices({
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: deviceId,
			success: function(res) {
				console.log("是否进入",res)
				//需要什么服务就用对应的services 
				services = res.services[0].uuid;
				that.getCharacteId() //6.0
				eventBus.$emit('connectionStatus', 2)
				connectionStatus = 2;
			}
		})
	},
	
	getCharacteId() {
		var that = this;
		uni.getBLEDeviceCharacteristics({
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: deviceId,
			// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
			serviceId: services,
			success: function(res) {
				console.log(res)
				for (var i = 0; i < res.characteristics.length; i++) { //2个值
					var model = res.characteristics[i]
					if (model.properties.write) {
						//model.uuid:用来写入的uuid值
						//this.sendMy()给设备写入
						characteristicId = model.uuid;
					}
					if (model.properties.notify) {
						//model.uuid:用来notify的uuid值
						notifyUuid = model.uuid;
						that.startNotice();
						const currentDate = new Date();
						const formattedDate = uni.$u.timeFormat(currentDate, 'yyyy-mm-dd hh:MM:ss');
						that.sendMy('TIME:' + formattedDate + ':48#',1);
					}
				}
				
			}
		})
	},
	
	
	//buffer允许写入的uuid
	sendMy(data,type) {
		// data = "NAME:600009#";
		console.log("发送给蓝牙版",data);
		//this.string2buffer-->字符串转换成ArrayBufer（设备接收数据的格式ArrayBufer）
		var that = this;
		var buff;
		if(type == 1){
			var uint8Array = that.stringToUint8Array(data)
			buff = uint8Array.buffer;
		}else{
			buff = that.string2buffer(data);  //9.0
		}
		console.log("buff",buff);
		uni.writeBLECharacteristicValue({
			// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
			deviceId: deviceId,
			// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
			serviceId: services,
			// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
			characteristicId: characteristicId, //第二步写入的特征值
			// 这里的value是ArrayBuffer类型
			value: buff,
			success: function(res) {
				//此时设备已接收到你写入的数据
				console.log("写入成功")
			},
			fail: function(err) {
				console.log(err)
			},
			complete: function() {
				console.log("调用结束");
			}
		})
	},
		
		
	startNotice() {
		var that = this;
		uni.notifyBLECharacteristicValueChange({
			state: true, // 启用 notify 功能
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
			deviceId: deviceId,
			// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
			serviceId: services,
			// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
			characteristicId: notifyUuid, //第一步 开启监听 notityid  第二步发送指令 write
			success(res) {
				//接收蓝牙返回消息
				uni.onBLECharacteristicValueChange((sjRes)=>{
					// 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据，
					//所以需要通过一个方法转换成字符串
					var nonceId = that.ab2hex(sjRes.value)//10.0
					console.log('蓝牙板回复协议',nonceId)
					$api('device.bluetoothTestResults',{protocol:nonceId}).then(res => {})
				})
			},
			fail(err) {
				console.log(err)
			}
		})
	},
	
	
	stringToUint8Array(str) {  
	  const len = str.length;  
	   const arr = new Uint8Array(len);  
	   for (let i = 0; i < len; i++) {  
	     arr[i] = str.charCodeAt(i); // 将字符的 Unicode 编码转换为无符号8位整数  
	   }  
	   return arr;  
	},  
	
	
	string2buffer(str) {
		let val = ""
		if (!str) return;
		let length = str.length;
		let index = 0;
		let array = []
		while (index < length) {
			array.push(str.substring(index, index + 2));
			index = index + 2;
		}
		val = array.join(",");
		// 将16进制转化为ArrayBuffer
		console.log("val",val)
		return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function(h) {
			return parseInt(h, 16)
		})).buffer
	},
	ab2hex(buffer) {
		const hexArr = Array.prototype.map.call(
			new Uint8Array(buffer),
			function (bit) {
				return ('00' + bit.toString(16)).slice(-2)
			}
		)
		return hexArr.join('')
	},




	
}
